package com.chucang.shucang.usr.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chucang.shucang.common.base.constant.CommonConstant;
import com.chucang.shucang.common.base.exception.FastException;
import com.chucang.shucang.common.base.redis.RedisUtil;
import com.chucang.shucang.common.base.utils.OpsUtil;
import com.chucang.shucang.common.base.utils.R;
import com.chucang.shucang.common.base.utils.Sm4Util;
import com.chucang.shucang.common.mq.constant.RabbitConstant;
import com.chucang.shucang.common.mq.to.TransferTO;
import com.chucang.shucang.common.security.annotation.Inner;
import com.chucang.shucang.common.security.utils.SecurityUtil;
import com.chucang.shucang.usr.constant.UsrCacheConstant;
import com.chucang.shucang.usr.constant.UsrCommonConstant;
import com.chucang.shucang.usr.entity.RealNameAuthEntity;
import com.chucang.shucang.usr.entity.UserBillRecordEntity;
import com.chucang.shucang.usr.entity.UserWalletEntity;
import com.chucang.shucang.usr.exception.UsrErrorCode;
import com.chucang.shucang.usr.feign.BacService;
import com.chucang.shucang.usr.feign.OmsService;
import com.chucang.shucang.usr.feign.TtpService;
import com.chucang.shucang.usr.feign.vo.BlindBoxOrderBaseResVO;
import com.chucang.shucang.usr.feign.vo.CollectionOrderBaseResVO;
import com.chucang.shucang.usr.feign.vo.PayInfoVO;
import com.chucang.shucang.usr.feign.vo.WithdrawChargeVO;
import com.chucang.shucang.usr.service.RealNameAuthService;
import com.chucang.shucang.usr.service.UserBillRecordService;
import com.chucang.shucang.usr.service.UserWalletService;
import com.chucang.shucang.usr.vo.*;
import com.github.yitter.idgen.YitIdHelper;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 用户钱包
 *
 * @author flitsneak flitsneak@gmail.com
 * @since 1.0.0 2022-10-22
 */
@RestController
@RequestMapping("/userwallet")
@RequiredArgsConstructor
@Api(tags = "用户钱包")
public class UserWalletController {

    private final UserWalletService userWalletService;
    private final UserBillRecordService userBillRecordService;
    private final RealNameAuthService realNameAuthService;
    private final RabbitTemplate rabbitTemplate;
    private final OmsService omsService;
    private final TtpService ttpService;
    private final BacService bacService;
    private final RedisUtil redisUtil;

    @Value("${encrypt.secret.sm4}")
    private String sm4;

    /**
     * 支付宝订单支付
     *
     * @param orderSn 订单编号
     * @return r
     */
    @GetMapping("/payForBlindBoxOrderByAliPay/{orderSn}")
    public R<AlipayTradeAppPayResponse> payForBlindBoxOrderByAliPay(@PathVariable String orderSn) {
        //是否开通钱包
        LambdaQueryWrapper<UserWalletEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserWalletEntity::getUserId, SecurityUtil.getUser().getId())
                .select();
        UserWalletEntity one = userWalletService.getOne(queryWrapper);
        if (Objects.isNull(one)) {
            return R.failed(UsrErrorCode.NO_WALLET_FOUND.getCode(), UsrErrorCode.NO_WALLET_FOUND.getMsg());
        }
        //检验订单时间是否超过时效
        R<BlindBoxOrderBaseResVO> orderBaseResVO = omsService.checkBlindBoxOrder(orderSn);
        BlindBoxOrderBaseResVO boxOrderBaseResVO = OpsUtil.of(orderBaseResVO)
                .assertCode(CommonConstant.SUCCESS, e -> new FastException("获取盲盒订单详情失败!"))
                .getData()
                .get();
        Date now = new Date();
        DateTime endTime = DateUtil.offsetMinute(boxOrderBaseResVO.getCreateTime(), 6);
        //未超过时效
        if (now.getTime() < endTime.getTime()) {
            if (redisUtil.setIfAbsent(String.format(UsrCacheConstant.USER_ALIPAY, boxOrderBaseResVO.getUserId()), orderSn, 3, TimeUnit.MINUTES)) {
                //调用alipay
                PayInfoVO payInfoVO = new PayInfoVO();
                payInfoVO
                        .setOrderSn(boxOrderBaseResVO.getOrderSn())
                        .setOrderAmount(boxOrderBaseResVO.getOrderAmount().toPlainString())
                        .setPrice(boxOrderBaseResVO.getOrderAmount().divide(new BigDecimal(boxOrderBaseResVO.getOrderNum()), 0, RoundingMode.HALF_EVEN).toPlainString())
                        .setQuantity((long) boxOrderBaseResVO.getOrderNum())
                        .setProductName(boxOrderBaseResVO.getBbName())
                        .setProductId(boxOrderBaseResVO.getBbId().toString())
                        .setSubject("购买盲盒" + boxOrderBaseResVO.getBbName() + "*" + boxOrderBaseResVO.getOrderNum())
                        .setType(1);
                return ttpService.payForOrder(payInfoVO);
            } else {
                return R.failed(UsrErrorCode.ALIPAY_REPEAT.getCode(), UsrErrorCode.ALIPAY_REPEAT.getMsg());
            }
        } else {
            return R.failed(UsrErrorCode.ORDER_OVERDUE.getCode(), UsrErrorCode.ORDER_OVERDUE.getMsg());
        }
    }

    /**
     * 盲盒钱包支付
     *
     * @param orderSn 订单号
     * @return r
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/payForBlindBoxOrderByWallet/{orderSn}")
    public R<AlipayTradeAppPayResponse> payForBlindBoxOrderByWallet(@PathVariable String orderSn) {
        //是否开通钱包？
        LambdaQueryWrapper<UserWalletEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserWalletEntity::getUserId, SecurityUtil.getUser().getId())
                .select();
        UserWalletEntity one = userWalletService.getOne(queryWrapper);
        if (Objects.isNull(one)) {
            return R.failed(UsrErrorCode.NO_WALLET_FOUND.getCode(), UsrErrorCode.NO_WALLET_FOUND.getMsg());
        }
        //钱包支付
        //检验订单时间是否超过时效
        R<BlindBoxOrderBaseResVO> orderBaseResVO = omsService.checkBlindBoxOrder(orderSn);
        BlindBoxOrderBaseResVO boxOrderBaseResVO = OpsUtil.of(orderBaseResVO)
                .assertCode(CommonConstant.SUCCESS, e -> new FastException("获取订单详情失败"))
                .getData()
                .get();
        Date now = new Date();
        DateTime endTime = DateUtil.offsetMinute(boxOrderBaseResVO.getCreateTime(), 6);
        //未超过时效
        if (now.getTime() < endTime.getTime()) {
            //余额不足
            if (one.getBalance().compareTo(boxOrderBaseResVO.getOrderAmount()) < 0) {
                return R.failed(UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getCode(), UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getMsg());
            } else {
                Long userId = boxOrderBaseResVO.getUserId();
                if (redisUtil.setIfAbsent(String.format(UsrCacheConstant.USER_WALLET_PAY, userId), orderSn, 3, TimeUnit.MINUTES)) {
                    //扣减钱包余额
                    UserWalletEntity byId = userWalletService.getById(one.getId());
                    BigDecimal subtract = byId.getBalance().subtract(boxOrderBaseResVO.getOrderAmount());
                    if (subtract.compareTo(new BigDecimal("0")) < 0) {
                        return R.failed(UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getCode(), UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getMsg());
                    }
                    LambdaUpdateWrapper<UserWalletEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper.eq(UserWalletEntity::getId, one.getId())
                            .set(UserWalletEntity::getBalance, subtract);
                    userWalletService.update(lambdaUpdateWrapper);
                    userWalletService.blindBoxOrderSuccess(boxOrderBaseResVO, UsrCommonConstant.FROM_WALLET);
                    return R.ok();
                } else {
                    //不可重复操作
                    return R.failed(UsrErrorCode.WALLET_PAY_REPEAT.getCode(), UsrErrorCode.WALLET_PAY_REPEAT.getMsg());
                }
            }
        } else {
            return R.failed(UsrErrorCode.ORDER_OVERDUE.getCode(), UsrErrorCode.ORDER_OVERDUE.getMsg());
        }
    }

    /**
     * 支付宝订单支付
     *
     * @param orderSn 订单编号
     * @return r
     */
    @GetMapping("/payForCollectionOrderByAliPay/{orderSn}")
    public R<AlipayTradeAppPayResponse> payForCollectionOrderByAliPay(@PathVariable String orderSn) {
        //是否开通钱包
        LambdaQueryWrapper<UserWalletEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserWalletEntity::getUserId, SecurityUtil.getUser().getId())
                .select();
        UserWalletEntity one = userWalletService.getOne(queryWrapper);
        if (Objects.isNull(one)) {
            return R.failed(UsrErrorCode.NO_WALLET_FOUND.getCode(), UsrErrorCode.NO_WALLET_FOUND.getMsg());
        }
        //检验订单时间是否超过时效
        R<CollectionOrderBaseResVO> orderBaseResVO = omsService.checkCollectionOrder(orderSn);
        CollectionOrderBaseResVO colectionOrderBaseResVO = OpsUtil.of(orderBaseResVO)
                .assertCode(CommonConstant.SUCCESS, e -> new FastException("获取订单详情失败"))
                .getData()
                .get();
        Date now = new Date();
        DateTime endTime = DateUtil.offsetMinute(colectionOrderBaseResVO.getCreateTime(), 6);
        //未超过时效
        if (now.getTime() < endTime.getTime()) {
            if (redisUtil.setIfAbsent(String.format(UsrCacheConstant.USER_ALIPAY, colectionOrderBaseResVO.getUserId()), orderSn, 3, TimeUnit.MINUTES)) {
                //调用alipay
                PayInfoVO payInfoVO = new PayInfoVO();
                payInfoVO
                        .setOrderSn(colectionOrderBaseResVO.getOrderSn())
                        .setOrderAmount(colectionOrderBaseResVO.getOrderAmount().toPlainString())
                        .setPrice(colectionOrderBaseResVO.getOrderAmount().divide(new BigDecimal(colectionOrderBaseResVO.getOrderNum()), 0, RoundingMode.HALF_EVEN).toPlainString())
                        .setQuantity((long) colectionOrderBaseResVO.getOrderNum())
                        .setProductName(colectionOrderBaseResVO.getDcName())
                        .setProductId(colectionOrderBaseResVO.getCollectionId().toString())
                        .setSubject("购买盲盒" + colectionOrderBaseResVO.getDcName() + "*" + colectionOrderBaseResVO.getOrderNum())
                        .setType(0);
                return ttpService.payForOrder(payInfoVO);
            } else {
                return R.failed(UsrErrorCode.ALIPAY_REPEAT.getCode(), UsrErrorCode.ALIPAY_REPEAT.getMsg());
            }
        } else {
            return R.failed(UsrErrorCode.ORDER_OVERDUE.getCode(), UsrErrorCode.ORDER_OVERDUE.getMsg());
        }
    }

    /**
     * 钱包支付
     *
     * @param orderSn 订单号
     * @return r
     */
    @Transactional(rollbackFor = Exception.class)
    @GetMapping("/payForCollectionOrderByWallet/{orderSn}")
    public R<AlipayTradeAppPayResponse> payForCollectionOrderByWallet(@PathVariable String orderSn) {
        //是否开通钱包？
        LambdaQueryWrapper<UserWalletEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserWalletEntity::getUserId, SecurityUtil.getUser().getId())
                .select();
        UserWalletEntity one = userWalletService.getOne(queryWrapper);
        if (Objects.isNull(one)) {
            return R.failed(UsrErrorCode.NO_WALLET_FOUND.getCode(), UsrErrorCode.NO_WALLET_FOUND.getMsg());
        }
        //钱包支付
        //检验订单时间是否超过时效
        R<CollectionOrderBaseResVO> orderBaseResVO = omsService.checkCollectionOrder(orderSn);
        CollectionOrderBaseResVO collectionOrderBaseResVO = OpsUtil.of(orderBaseResVO)
                .assertCode(CommonConstant.SUCCESS, e -> new FastException("获取订单详情失败"))
                .getData()
                .get();
        Date now = new Date();
        DateTime endTime = DateUtil.offsetMinute(collectionOrderBaseResVO.getCreateTime(), 6);
        //未超过时效
        if (now.getTime() < endTime.getTime()) {
            //余额不足
            if (one.getBalance().compareTo(collectionOrderBaseResVO.getOrderAmount()) < 0) {
                return R.failed(UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getCode(), UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getMsg());
            } else {
                Long userId = collectionOrderBaseResVO.getUserId();
                if (redisUtil.setIfAbsent(String.format(UsrCacheConstant.USER_WALLET_PAY, userId), orderSn, 3, TimeUnit.MINUTES)) {
                    //扣减钱包余额
                    UserWalletEntity byId = userWalletService.getById(one.getId());
                    BigDecimal subtract = byId.getBalance().subtract(collectionOrderBaseResVO.getOrderAmount());
                    if (subtract.compareTo(new BigDecimal("0")) < 0) {
                        return R.failed(UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getCode(), UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getMsg());
                    }
                    LambdaUpdateWrapper<UserWalletEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper.eq(UserWalletEntity::getUserId, userId)
                            .set(UserWalletEntity::getBalance, subtract);
                    userWalletService.update(lambdaUpdateWrapper);
                    userWalletService.collectionOrderSuccess(collectionOrderBaseResVO, UsrCommonConstant.FROM_WALLET);
                    return R.ok();
                } else {
                    //不可重复操作
                    return R.failed(UsrErrorCode.WALLET_PAY_REPEAT.getCode(), UsrErrorCode.WALLET_PAY_REPEAT.getMsg());
                }
            }
        } else {
            return R.failed(UsrErrorCode.ORDER_OVERDUE.getCode(), UsrErrorCode.ORDER_OVERDUE.getMsg());
        }
    }

    /**
     * 创建我的钱包
     *
     * @return r
     */
    @PostMapping("/createMyWallet")
    public R<String> createMyWallet(@Valid @RequestBody UserWalletCreateVO userWalletCreateVO) {
        //查找是否已存在
        LambdaQueryWrapper<UserWalletEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserWalletEntity::getUserId, SecurityUtil.getUser().getId())
                .select();
        UserWalletEntity one = userWalletService.getOne(lambdaQueryWrapper);
        if (Objects.nonNull(one)) {
            return R.ok();
        }
        //查找是否实名认证
        LambdaQueryWrapper<RealNameAuthEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RealNameAuthEntity::getUserId,SecurityUtil.getUser().getId());
        RealNameAuthEntity authServiceOne = realNameAuthService.getOne(queryWrapper);
        if (Objects.isNull(authServiceOne)){
            return R.failed(UsrErrorCode.NO_REAL_NAME_AUTH.getCode(),UsrErrorCode.NO_REAL_NAME_AUTH.getMsg());
        }
        UserWalletEntity userWalletEntity = new UserWalletEntity();
        userWalletEntity.setUserId(SecurityUtil.getUser().getId());
        userWalletEntity.setBalance(new BigDecimal("0"));
        userWalletEntity.setAlipay(Sm4Util.encode(sm4, userWalletCreateVO.getAlipay()));
        userWalletService.save(userWalletEntity);
        return R.ok();
    }

    /**
     * 提现到支付宝
     *
     * @return r
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/withdrawBalanceToAli")
    public R<String> withdrawBalanceToAli(@Valid @RequestBody WalletWithdrawBalanceVO walletWithdrawBalanceVO) {
        //查询余额
        LambdaQueryWrapper<UserWalletEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Long userId = SecurityUtil.getUser().getId();
        lambdaQueryWrapper.eq(UserWalletEntity::getUserId, userId)
                .select();
        UserWalletEntity one = userWalletService.getOne(lambdaQueryWrapper);
        if (Objects.isNull(one)) {
            return R.failed(UsrErrorCode.NO_WALLET_FOUND.getCode(), UsrErrorCode.NO_WALLET_FOUND.getMsg());
        }
        if (CharSequenceUtil.isBlank(one.getAlipay())) {
            return R.failed(UsrErrorCode.NO_ALIPAY_ACCOUNT_FOUND.getCode(), UsrErrorCode.NO_ALIPAY_ACCOUNT_FOUND.getMsg());
        }
        if (Integer.parseInt(walletWithdrawBalanceVO.getAmount()) < 100) {
            return R.failed(UsrErrorCode.MINIMUM_WITHDRAWAL_LIMIT.getCode(), UsrErrorCode.MINIMUM_WITHDRAWAL_LIMIT.getMsg());
        }
        BigDecimal withdraw = new BigDecimal(walletWithdrawBalanceVO.getAmount());
        if (one.getBalance().compareTo(withdraw) < 0) {
            return R.failed(UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getCode(), UsrErrorCode.WALLET_INSUFFICIENT_BALANCE.getMsg());
        }
        //实名认证信息获取
        LambdaQueryWrapper<RealNameAuthEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RealNameAuthEntity::getUserId, userId)
                .select();
        RealNameAuthEntity authEntity = realNameAuthService.getOne(queryWrapper);
        if (Objects.isNull(authEntity)) {
            return R.failed(UsrErrorCode.NO_REAL_NAME_AUTH.getCode(), UsrErrorCode.NO_REAL_NAME_AUTH.getMsg());
        }
        //提现费率查询
        R<WithdrawChargeVO> balanceCharge = bacService.getWithdrawBalanceCharge();
        WithdrawChargeVO chargeVO = OpsUtil.of(balanceCharge)
                .assertCode(CommonConstant.SUCCESS, e -> new FastException("查询提现费率异常"))
                .getData()
                .get();

        BigDecimal charge = new BigDecimal(chargeVO.getChargeRate());
        //扣除费率
        BigDecimal chargeRate = charge.divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
        //扣除手续金额
        BigDecimal chargeAmount = withdraw.multiply(chargeRate);
        //阿里转账金额
        String transfer = withdraw.subtract(chargeAmount).toPlainString();
        //生成账单
        UserBillRecordEntity billRecordEntity = new UserBillRecordEntity();

        long l = YitIdHelper.nextId();
        long sub = userId % 1000000;
        String billSn = String.valueOf(l) + sub;
        billRecordEntity.setBillType(2);
        billRecordEntity.setCharge(chargeAmount);
        billRecordEntity.setAmount(withdraw);
        billRecordEntity.setUserId(userId);
        billRecordEntity.setBillSn(billSn);
        billRecordEntity.setId(l);

        TransferTO transferTO = new TransferTO();
        transferTO
                .setBillSn(billSn)
                .setUsername(Sm4Util.decode(sm4, authEntity.getRealName()))
                .setBillTitle("钱包提现")
                .setPayeeAccount(Sm4Util.decode(sm4, one.getAlipay()))
                .setTransAmount(transfer)
                .setWithdrawAmount(withdraw);
        //mq顺序消费
        rabbitTemplate.convertAndSend(RabbitConstant.PAY_EXCHANGE, RabbitConstant.ALIPAY_WITHDRAW_KEY, transferTO);
        return R.ok();
    }

    /**
     * 钱包充值
     *
     * @param walletRechargeVO w
     * @return r
     */
    @PostMapping("/walletRecharge")
    public R<AlipayTradeAppPayResponse> walletRecharge(@Valid @RequestBody WalletRechargeVO walletRechargeVO) {
        //是否开通钱包
        LambdaQueryWrapper<UserWalletEntity> queryWrapper = new LambdaQueryWrapper<>();
        Long userId = SecurityUtil.getUser().getId();
        queryWrapper.eq(UserWalletEntity::getUserId, userId)
                .select();
        UserWalletEntity one = userWalletService.getOne(queryWrapper);
        if (Objects.isNull(one)) {
            return R.failed(UsrErrorCode.NO_WALLET_FOUND.getCode(), UsrErrorCode.NO_WALLET_FOUND.getMsg());
        }
        //创建账单
        UserBillRecordEntity userBillRecordEntity = new UserBillRecordEntity();
        long l = YitIdHelper.nextId();
        long sub = userId % 1000000;
        String billSn = String.valueOf(l) + sub;
        userBillRecordEntity.setUserId(userId);
        userBillRecordEntity.setOrderSn(billSn);
        userBillRecordEntity.setAmount(new BigDecimal(walletRechargeVO.getAmount()));
        userBillRecordEntity.setBillType(1);
        userBillRecordEntity.setId(l);

        userBillRecordService.save(userBillRecordEntity);

        //调用alipay
        PayInfoVO payInfoVO = new PayInfoVO();
        payInfoVO
                .setBillSn(billSn)
                .setOrderAmount(walletRechargeVO.getAmount())
                .setPrice(walletRechargeVO.getAmount())
                .setQuantity(1L)
                .setProductName("钱包充值")
                .setProductId(String.valueOf(l))
                .setSubject("钱包充值：" + walletRechargeVO.getAmount() + "元")
                .setType(2);
        return ttpService.payForOrder(payInfoVO);
    }

    /**
     * 获取我的钱包信息
     *
     * @return r
     */
    @GetMapping("/myWallet")
    public R<MyWalletInfoResVO> myWallet() {
        Long userId = SecurityUtil.getUser().getId();
        LambdaQueryWrapper<UserWalletEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserWalletEntity::getUserId, userId)
                .select();
        UserWalletEntity one = userWalletService.getOne(lambdaQueryWrapper);
        if (Objects.isNull(one)) {
            return R.failed(UsrErrorCode.NO_WALLET_FOUND.getCode(), UsrErrorCode.NO_WALLET_FOUND.getMsg());
        }
        MyWalletInfoResVO myWalletInfoResVO = new MyWalletInfoResVO();
        BeanUtil.copyProperties(one, myWalletInfoResVO);
        myWalletInfoResVO.setAlipay(Sm4Util.decode(sm4, one.getAlipay()));
        return R.ok(myWalletInfoResVO);
    }

    /**
     * 更新支付宝信息
     *
     * @return
     */
    @PostMapping("/updateAliPayInfo")
    public R<String> updateAliPayInfo(@Valid @RequestBody AliPayUpdateInfoVO aliPayUpdateInfoVO) {
        Long userId = SecurityUtil.getUser().getId();
        LambdaQueryWrapper<UserWalletEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserWalletEntity::getUserId, userId)
                .select();
        UserWalletEntity one = userWalletService.getOne(lambdaQueryWrapper);
        if (Objects.isNull(one)) {
            return R.failed(UsrErrorCode.NO_WALLET_FOUND.getCode(), UsrErrorCode.NO_WALLET_FOUND.getMsg());
        }
        LambdaUpdateWrapper<UserWalletEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserWalletEntity::getId, one.getId())
                .set(UserWalletEntity::getAlipay, aliPayUpdateInfoVO.getAlipay());
        userWalletService.update(lambdaUpdateWrapper);
        return R.ok();
    }

    @Inner
    @PostMapping("/walletDeduction")
    public R<String> walletDeduction(@RequestBody WalletDeductionVO walletDeductionVO) {
        //获取钱包信息
        LambdaQueryWrapper<UserWalletEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserWalletEntity::getUserId, walletDeductionVO.getUserId())
                .select();
        UserWalletEntity one = userWalletService.getOne(lambdaQueryWrapper);
        if (one.getBalance().compareTo(walletDeductionVO.getAmount()) < 0) {
            return R.failed();
        }
        LambdaUpdateWrapper<UserWalletEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserWalletEntity::getId, one.getId())
                .set(UserWalletEntity::getBalance, one.getBalance().subtract(walletDeductionVO.getAmount()));
        userWalletService.update(lambdaUpdateWrapper);
        return R.ok();
    }

}